const { Service } = require('egg');
const myDate = require('../utils/myDate');
const { sendEmail } = require('../utils/email');
const { emailThrottleDuration } = require('../config/index');
const { v4: uuidv4 } = require('uuid');
class MeetingService extends Service {
  async addMeeting(meetingInfo) {
    meetingInfo.create_time = myDate.getNowDate();
    meetingInfo.update_time = myDate.getNowDate();
    const token = this.ctx.request.header.authorization?.slice(7);
    const userInfo = this.app.jwt.decode(token);
    meetingInfo.create_by = userInfo.id;
    meetingInfo.update_by = userInfo.id;
    const res = await this.app.mysql.insert('meeting', {
      name: meetingInfo.name,
      create_by: userInfo.id,
      update_by: userInfo.id,
      create_time: myDate.getNowDate(),
      update_time: myDate.getNowDate(),
    });
    if (res.affectedRows) {
      return true;
    }
    return false;
  }

  async updateMeeting(meetingInfo) {
    meetingInfo.update_time = myDate.getNowDate();
    const token = this.ctx.request.header.authorization?.slice(7);
    const userInfo = this.app.jwt.decode(token);
    meetingInfo.update_by = userInfo.id;
    const target = {
      name: meetingInfo.name,
      update_by: userInfo.id,
      update_time: myDate.getNowDate(),
    };
    if (meetingInfo.score_panel) {
      target.score_panel = meetingInfo.score_panel;
    }
    const res = await this.app.mysql.update(
      'meeting',
      target,
      { where: { id: meetingInfo.id } }
    );
    if (res.affectedRows) {
      return true;
    }
    return false;
  }

  async getMeetings(pageNum, pageSize, name) {
    let where = '';
    if (name) {
      where = `WHERE name LIKE '%${name}%'`;
    }
    const total = await this.app.mysql.count('meeting', where);
    const res = await this.app.mysql.query(
      `SELECT * FROM meeting ${where} LIMIT ?, ?`,
      [ (pageNum - 1) * pageSize, pageSize ]
    );
    if (res) {
      return {
        meetings: res,
        total,
      };
    }
    return false;
  }

  async getMeeting(id) {
    const res = await this.app.mysql.get('meeting', { id });
    if (res) {
      const users = await this.app.mysql.query(
        `SELECT u.* 
        FROM meeting_user mt 
        JOIN user u ON u.id = mt.user_id
        where mt.meeting_id = ${res.id}`
      );
      const interviews = await this.app.mysql.query(
        `SELECT i.id,i.interviewer_id,i.user_id,i.meeting_id,i.begin,i.end,i.is_send_email,i.state,i.create_by,i.update_by,u.name,u.home,u.email,u.phone,u.sex,u.birth_day
        FROM interview i 
        JOIN user u ON u.id = i.user_id
        WHERE i.meeting_id = ${res.id}`
      );
      return {
        res,
        users,
        interviews,
      };
    }
    return false;
  }

  async delMeeting(ids) {
    const res = await this.app.mysql.query(
      `delete from meeting where id in (${ids.join(',')})`
    );
    if (res.affectedRows) {
      return {
        state: true,
        msg: '删除成功',
      };
    }
    return {
      state: false,
      msg: '删除失败',
    };
  }

  async addMeetingUsers(meetingId, userIds) {
    for (const id of userIds) {
      const isExit = await this.app.mysql.query(
        `SELECT * FROM meeting_user WHERE meeting_id = ${meetingId} AND user_id = ${id}`
      );
      if (isExit.length) {
        continue;
      }
      const res = await this.app.mysql.query(
        `INSERT INTO meeting_user (meeting_id, user_id) VALUES (${meetingId}, ${id})`
      );
      if (!res) {
        return {
          state: false,
          msg: '添加失败',
        };
      }
    }
    await this.ctx.service.meeting.updateInterView(meetingId);
    return {
      state: true,
      msg: '添加成功',
    };
  }

  async delMeetingUsers(meetingId, userIds) {
    const res = await this.app.mysql.query(
      `delete from meeting_user 
      where meeting_id = ${meetingId} 
      and user_id in (${userIds.join(',')})`
    );
    await this.ctx.service.meeting.updateInterView(meetingId);
    if (res.affectedRows) {
      return true;
    }
    return false;
  }

  async updateInterView(meetingId) {
    const curUser = await this.app.mysql.query(
      `SELECT user_id FROM meeting_user WHERE meeting_id = ${meetingId}`
    );
    const userIds = curUser.map(item => item.user_id);
    if (userIds.length) {
      await this.app.mysql.query(
        `delete from interview where meeting_id = ${meetingId} and user_id not in (${userIds.join(
        )})`
      );
    } else {
      await this.app.mysql.query(
        `delete from interview where meeting_id = ${meetingId}`
      );
      return;
    }
    for (let i = 0; i < userIds.length; i++) {
      const isExit = await this.app.mysql.query(
        `SELECT * FROM interview WHERE meeting_id = ${meetingId} AND user_id = ${userIds[i]}`
      );
      if (isExit.length) {
        continue;
      }
      await this.app.mysql.query(
        `INSERT INTO interview (meeting_id, user_id, state) VALUES (${meetingId}, ${userIds[i]}, '0')`
      );
    }
  }

  async sendEmail(meetingId, userId) {
    const isSend = await this.ctx.service.redis.get(`sendemail${meetingId}${userId}`);
    if (isSend) {
      return {
        state: false,
        msg: '冷却中，请稍后再试试',
      };
    }
    await this.ctx.service.redis.set(`sendemail${meetingId}${userId}`, true, emailThrottleDuration);
    const interview = await this.app.mysql.query(
      `SELECT * FROM interview WHERE meeting_id = ${meetingId} AND user_id = ${userId}`
    );
    if (!interview[0].begin || !interview[0].end) {
      return {
        state: false,
        msg: '面试时间未设置',
      };
    }
    if (!interview[0].interviewer_id) {
      return {
        state: false,
        msg: '面试官未设置',
      };
    }
    if (Number(interview[0].is_send_email) !== '1') {
      const uniqueId = uuidv4();
      await this.app.mysql.query(
        `UPDATE interview 
        SET is_send_email = '1', token = '${uniqueId}'
        WHERE meeting_id = ${meetingId} AND user_id = ${userId};`
      );
    }

    const meetData = await this.app.mysql.query(
      `SELECT * FROM meeting WHERE id = ${meetingId}`
    );
    const userData = await this.app.mysql.query(
      `SELECT * FROM user WHERE id = ${userId}`
    );
    const userEmail = userData[0].email;
    const htmlContent = `
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>面试邀请</title>
    </head>
    <body>
        <p>亲爱的${userData[0].name} 同学，您好！</p>
        <p>感谢关注PANDA校园招聘！现诚邀您参加${meetData[0].name}职位的视频面试。</p>
        <p>视频面试时请您尽量使用电脑端进行操作（大于73版本的Chrome内核浏览器或者firefox、opera浏览器），并打开相机权限。</p>
        <ul>
            <li>面试日期：2025年3月4日星期二</li>
            <li>面试时间：17:00</li>
            <li>面试时长：45分钟（可能视面试情况缩减或延长，请预留一定缓冲时间）</li>
            <li>面试形式：视频面试</li>
            <li>面试地点：</li>
        </ul>
        <h3>【注意】</h3>
        <ol>
            <li>如确定参加面试，请点击“参加”。</li>
            <li>如时间冲突，请点击“拒绝”，并反馈可面试时间。</li>
        </ol>
        <p>有任何问题，请联系hr: 17338763009</p>
        <p>请您确认是否参加</p>
        <p><a href="#" style="background-color: #007bff; color: white; padding: 10px 20px; text-decoration: none;">参加 / Yes</a> 
        <a href="#" style="background-color: #6c757d; color: white; padding: 10px 20px; text-decoration: none;">不参加 / No</a> 
        <a href="#" style="color: blue; text-decoration: underline;">更改面试时间 / Adjust the interview time</a></p>
    </body>
    </html>
    `;
    const res = await sendEmail(userEmail, 'PANDA校园招聘——应届生面试邀请函', htmlContent);
    if (res) {
      return {
        state: true,
        msg: '发送成功',
      };
    }
    return {
      state: false,
      msg: '发送失败',
    };
  }

  async updateInterViewTime(interview) {
    const target = { id: interview.interviewId, begin: interview.begin, end: interview.end };
    console.log(interview.interviewer_id);
    if (interview.interviewer_id) {
      target.interviewer_id = interview.interviewer_id;
    }
    const update = await this.app.mysql.update('interview', target);
    if (update) {
      return {
        state: true,
        msg: '修改成功',
      };
    }
    return {
      state: false,
      msg: '修改失败',
    };
  }

  async getInterView(userId, day) {
    const res = await this.app.mysql.query(
      `SELECT * FROM interview WHERE user_id = ${userId} AND DATE_FORMAT(begin, '%Y-%m-%d') = '${day}'`
    );
    if (res) {
      return res;
    }
    return false;
  }
}

module.exports = MeetingService;
